﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using YArchitech.LIB;
using YArchitech.LIB.YJKControls;
using YArchitech.MEP.Electric.Common;
using HYElectricCommon;

namespace YArchitech.Revit.MEP.Calculator
{
	public partial class CaculatRoomTypeManage : System.Windows.Forms.Form
	{
		public CaculatRoomTypeManage(string RoomTypeStr)
		{
			this.roomTypeList = RoomTypeStr.Split(new char[]
			{
				'-'
			});
			this.InitializeComponent();
			this.btnCancel.TabStop = false;
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			//base.Icon = Resource.YArchitechIcon;
			ToolTip toolTip = new ToolTip();
			toolTip.AutoPopDelay = 5000;
			toolTip.InitialDelay = 1000;
			toolTip.ReshowDelay = 50;
			toolTip.ShowAlways = true;
			toolTip.SetToolTip(this.BtnAdd, "添加");
			toolTip.SetToolTip(this.btnDelete, "删除");
			this.FillIllAndPowerTree(this.treeView1);
			if (this.roomTypeList != null && this.roomTypeList[0] != "")
			{
				TreeNode userFamilyNode = this.GetUserFamilyNode(this.roomTypeList[0]);
				if (userFamilyNode != null)
				{
					this.treeView1.SelectedNode = userFamilyNode;
				}
			}
			else
			{
				this.treeView1.SelectedNode = CaculatRoomTypeManage.GetFirstNode(this.treeView1.Nodes[0]);
			}
			if (this.roomTypeList != null && this.roomTypeList.Length >= 3 && this.roomTypeList[2].Trim() != "" && this.dataGridView1.DataSource != null)
			{
				for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i++)
				{
					DataGridViewRow dataGridViewRow = this.dataGridView1.Rows[i];
					if (dataGridViewRow.Cells["ID"].Value != null)
					{
						if (dataGridViewRow.Cells["ID"].Value.ToString() == this.roomTypeList[2].ToString())
						{
							this.dataGridView1.Rows[i].Selected = true;
						}
						else
						{
							this.dataGridView1.Rows[i].Selected = false;
						}
					}
				}
			}
		}

		public void FillIllAndPowerTree(TreeView tv)
		{
			string fileName = AssistFunc.GetAppRootPath() + "\\Data\\IlluminanceCal.db3";
			string text = Path.Combine(Product.WorkingLocation, "IlluminanceCal.db3");
			if (DataBaseTempFileOperate.IsExistFile(text))
			{
				if (!DataBaseTempFileOperate.IsSameVersion(fileName, text))
				{
					DataBaseTempFileOperate.CopyDBFile(fileName, Product.WorkingLocation);
				}
			}
			else
			{
				DataBaseTempFileOperate.CopyDBFile(fileName, Product.WorkingLocation);
			}
			SqLiteHelper.SqlLiteDatabase("Data Source=" + text + ";Initial Catalog=sqlite;Integrated Security=True;Max Pool Size=10");
			tv.Nodes.Clear();
			System.Data.DataTable dataTable = Database.ExecQuery(string.Format("select [Trade] from [IllAndPower]  group by [Trade]", Array.Empty<object>()));
			if (dataTable == null)
			{
				return;
			}
			for (int i = 0; i < dataTable.Rows.Count; i++)
			{
				TreeNode treeNode = new TreeNode(dataTable.Rows[i][0].ToString());
				System.Data.DataTable dataTable2 = Database.ExecQuery(string.Format("select [BuildingType] from [IllAndPower] where [Trade]='{0}' group by [BuildingType]", dataTable.Rows[i][0].ToString()));
				if (dataTable2 == null)
				{
					return;
				}
				for (int j = 0; j < dataTable2.Rows.Count; j++)
				{
					TreeNode node = new TreeNode(dataTable2.Rows[j][0].ToString());
					treeNode.Nodes.Add(node);
				}
				tv.Nodes.Add(treeNode);
			}
		}

		private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
		{
			try
			{
				if (e.Node.Parent != null)
				{
					if (this.treeView1.SelectedNode != null && this.treeView1.SelectedNode.Tag == null)
					{
						System.Data.DataTable dataTable = Database.ExecQuery(string.Format("select [ID],[Place] as 场所,[ReferencePlane] as 参考平面,[PowerDensityNowV] as 现行功率密度,[PowerDensityObjV] as 目标功率密度,[IlluminanceStandard] as 照度标准值,[GlareValue] as 统一标准值,[Ra] as 显色指数 from [IllAndPower] where [BuildingType]='{0}'", this.treeView1.SelectedNode.Text.Trim()));
						this.SetDatagridView(dataTable);
						TreeviewValue tag = new TreeviewValue(dataTable, false);
						this.treeView1.SelectedNode.Tag = tag;
						this.dataGridView1.Columns["ID"].Visible = false;
					}
					else
					{
						TreeviewValue treeviewValue = this.treeView1.SelectedNode.Tag as TreeviewValue;
						this.dataGridView1.Columns.Clear();
						this.dataGridView1.Refresh();
						this.SetDatagridView(treeviewValue.DataGv);
						this.dataGridView1.Columns["ID"].Visible = false;
					}
				}
			}
			catch (Exception)
			{
				MessageBox.Show("包含不正确的字符");
			}
		}

		public void SetDatagridView(DataTable dt)
		{
			this.dataGridView1.Refresh();
			this.dataGridView1.Columns.Clear();
			int num = 0;
			for (int i = 0; i < dt.Columns.Count; i++)
			{
				this.dataGridView1.Columns.Add(dt.Columns[i].ToString(), dt.Columns[i].ToString());
				if (num <= 0 && dt.Rows.Count > 0)
				{
					this.dataGridView1.Rows.Add(dt.Rows.Count);
				}
				for (int j = 0; j < dt.Rows.Count; j++)
				{
					this.dataGridView1.Rows[j].Cells[i].Value = dt.Rows[j][i].ToString().Trim();
				}
				num++;
			}
		}

		private TreeNode GetUserFamilyNode(string name)
		{
			TreeNode treeNode = null;
			foreach (object obj in this.treeView1.Nodes)
			{
				treeNode = CaculatRoomTypeManage.GetSelectedNode((TreeNode)obj, name);
				if (treeNode != null)
				{
					break;
				}
			}
			return treeNode;
		}

		public static TreeNode GetSelectedNode(TreeNode tn, string name)
		{
			TreeNode treeNode = null;
			if (tn != null)
			{
				if (tn.Text == name)
				{
					return tn;
				}
				foreach (object obj in tn.Nodes)
				{
					TreeNode treeNode2 = (TreeNode)obj;
					if (treeNode2.Text == name)
					{
						treeNode = treeNode2;
						break;
					}
					treeNode = CaculatRoomTypeManage.GetSelectedNode(treeNode2, name);
					if (treeNode != null)
					{
						break;
					}
				}
			}
			return treeNode;
		}

		private void btnSave_Click(object sender, EventArgs e)
		{
			this.SaveThisData();
			this.isEdit = false;
		}

		private int getLampTypeId(string typeName)
		{
			return Convert.ToInt32(Database.ExecQuery(string.Format("select [ID] from [LampType] where [LampType]='{0}'", typeName)).Rows[0][0]);
		}

		private void btnOK_Click(object sender, EventArgs e)
		{
			BuidingTypeClass.BuidingType = this.treeView1.SelectedNode.Text;
			if (this.dataGridView1.SelectedRows.Count > 0 && this.dataGridView1.SelectedRows[0] != null)
			{
				DataGridViewRow dataGridViewRow = this.dataGridView1.SelectedRows[0];
				if (dataGridViewRow.Cells["ID"].Value != null && dataGridViewRow.Cells["场所"].Value != null)
				{
					BuidingTypeClass.DataList1 = new DataBuidingType(dataGridViewRow.Cells["场所"].Value.ToString(), dataGridViewRow.Cells["参考平面"].Value.ToString(), dataGridViewRow.Cells["现行功率密度"].Value.ToString(), dataGridViewRow.Cells["目标功率密度"].Value.ToString(), dataGridViewRow.Cells["照度标准值"].Value.ToString(), dataGridViewRow.Cells["统一标准值"].Value.ToString(), dataGridViewRow.Cells["显色指数"].Value.ToString(), dataGridViewRow.Cells["ID"].Value.ToString());
				}
			}
			try
			{
				this.RefreshDataTable(this.treeView1.Nodes);
			}
			catch (Exception)
			{
				MessageBox.Show("提交发生异常！请检查录入的数据是否有重复。");
			}
		}

		public void SaveThisData()
		{
			try
			{
				if (this.RefreshDataTable(this.treeView1.Nodes))
				{
					MessageBox.Show("保存成功！");
				}
				else
				{
					MessageBox.Show("保存失败！");
				}
			}
			catch (Exception)
			{
				MessageBox.Show("提交发生异常！请检查录入的数据是否有重复。");
			}
		}

		public bool RefreshDataTable(TreeNodeCollection aNodes)
		{
			foreach (string arg in this.DeleteId)
			{
				Database.ExecuteCommand(string.Format("delete from [IllAndPower] where [ID]='{0}'", arg));
			}
			this.DeleteId.Clear();
			foreach (object obj in aNodes)
			{
				TreeNode treeNode = (TreeNode)obj;
				TreeviewValue treeviewValue = treeNode.Tag as TreeviewValue;
				if (treeviewValue != null && treeviewValue.IsEdit)
				{
					DataTable dataGv = treeviewValue.DataGv;
					int i = 0;
					while (i < dataGv.Rows.Count)
					{
						string text = this.treeView1.SelectedNode.Text;
						string text2 = this.treeView1.SelectedNode.Parent.Text;
						if (dataGv != null && dataGv.Rows[i]["ID"].ToString() != "")
						{
							try
							{
								Database.ExecuteCommand(string.Format("update [IllAndPower] set [Place]='{0}',[ReferencePlane]='{1}',[PowerDensityNowV]='{2}',[PowerDensityObjV]='{3}',[IlluminanceStandard]='{4}',[GlareValue]='{5}',[Ra]='{6}' where [ID]='{7}'", new object[]
								{
									dataGv.Rows[i]["场所"].ToString(),
									dataGv.Rows[i]["参考平面"].ToString(),
									dataGv.Rows[i]["现行功率密度"].ToString(),
									dataGv.Rows[i]["目标功率密度"].ToString(),
									dataGv.Rows[i]["照度标准值"].ToString(),
									dataGv.Rows[i]["统一标准值"].ToString(),
									dataGv.Rows[i]["显色指数"].ToString(),
									dataGv.Rows[i]["ID"].ToString()
								}));
								goto IL_375;
							}
							catch (Exception)
							{
								goto IL_375;
							}
							goto IL_211;
						}
						goto IL_211;
						IL_375:
						i++;
						continue;
						IL_211:
						if (dataGv.Rows[i]["场所"] != null && dataGv.Rows[i]["场所"].ToString().Trim() != "")
						{
							try
							{
								Database.ExecuteCommand(string.Format("insert into [IllAndPower] ([Trade],[BuildingType],[Place],[ReferencePlane],[PowerDensityNowV],[PowerDensityObjV],[IlluminanceStandard],[GlareValue],[Ra]) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')", new object[]
								{
									text2,
									text,
									dataGv.Rows[i]["场所"].ToString(),
									dataGv.Rows[i]["参考平面"].ToString(),
									dataGv.Rows[i]["现行功率密度"].ToString(),
									dataGv.Rows[i]["目标功率密度"].ToString(),
									dataGv.Rows[i]["照度标准值"].ToString(),
									dataGv.Rows[i]["统一标准值"].ToString(),
									dataGv.Rows[i]["显色指数"].ToString()
								}));
								goto IL_375;
							}
							catch (Exception)
							{
								goto IL_375;
							}
						}
						MessageBox.Show("场所不能为空");
						return false;
					}
				}
				if (treeNode.Nodes.Count > 0)
				{
					this.RefreshDataTable(treeNode.Nodes);
				}
			}
			return true;
		}

		public static TreeNode GetFirstNode(TreeNode tn)
		{
			TreeNode treeNode = null;
			if (tn != null)
			{
				if (tn.Nodes == null || tn.Nodes.Count < 1)
				{
					treeNode = tn;
				}
				else
				{
					foreach (object obj in tn.Nodes)
					{
						treeNode = CaculatRoomTypeManage.GetFirstNode((TreeNode)obj);
						if (treeNode != null)
						{
							break;
						}
					}
				}
			}
			return treeNode;
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			if (this.isEdit)
			{
				MessageBoxButtons buttons = MessageBoxButtons.YesNo;
				if (MessageBox.Show("是否保存?", "盈建科提示", buttons) == DialogResult.Yes)
				{
					this.SaveThisData();
				}
			}
		}

		private void lbAddRows_Click(object sender, EventArgs e)
		{
		}

		private void label2_Click(object sender, EventArgs e)
		{
		}

		private void treeView1_Leave(object sender, EventArgs e)
		{
			if (this.treeView1.SelectedNode != null)
			{
				this.treeView1.SelectedNode.BackColor = System.Drawing.Color.Gray;
			}
		}

		private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
		{
			if (this.treeView1.SelectedNode != null && this.treeView1.SelectedNode.Parent != null)
			{
				this.treeView1.SelectedNode.BackColor = System.Drawing.Color.Empty;
				DataTable dataGv = this.DataGridToDataTable(this.dataGridView1);
				(this.treeView1.SelectedNode.Tag as TreeviewValue).DataGv = dataGv;
			}
		}

		public DataTable DataGridToDataTable(DataGridView dv)
		{
			System.Data.DataTable dataTable = new DataTable();
			for (int i = 0; i < dv.Columns.Count; i++)
			{
				DataColumn dataColumn = new DataColumn();
				dataColumn.ColumnName = dv.Columns[i].HeaderText.ToString();
				dataTable.Columns.Add(dataColumn);
			}
			for (int j = 0; j < dv.Rows.Count; j++)
			{
				DataRow dataRow = dataTable.NewRow();
				for (int k = 0; k < dv.Columns.Count; k++)
				{
					dataRow[k] = dv.Rows[j].Cells[k].Value;
				}
				dataTable.Rows.Add(dataRow);
			}
			return dataTable;
		}

		private void btnDelete_Click(object sender, EventArgs e)
		{
			if (this.dataGridView1.SelectedRows.Count <= 0)
			{
				MessageBox.Show("请选择要删除的“照度要求及功率密度”参数行！", "盈建科提示");
				return;
			}
			if (this.dataGridView1.SelectedRows[0].Index != this.dataGridView1.Rows.Count && DialogResult.Yes == MessageBox.Show("是否要将选中项删除？", "照度计算数据库管理器", MessageBoxButtons.YesNo))
			{
				foreach (object obj in this.dataGridView1.SelectedRows)
				{
					DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
					if (dataGridViewRow.Cells["ID"].Value != null && dataGridViewRow.Cells["ID"].Value.ToString() != "")
					{
						this.DeleteId.Add(dataGridViewRow.Cells["ID"].Value.ToString());
						this.dataGridView1.Rows.Remove(dataGridViewRow);
					}
					else
					{
						this.dataGridView1.Rows.Remove(dataGridViewRow);
					}
				}
			}
			DataTable dataGv = this.DataGridToDataTable(this.dataGridView1);
			(this.treeView1.SelectedNode.Tag as TreeviewValue).DataGv = dataGv;
			if (this.dataGridView1.CurrentRow == null || this.dataGridView1.Rows[this.dataGridView1.CurrentCell.RowIndex].Cells[0].Value == null)
			{
				if (this.dataGridView1.Rows.Count > 0)
				{
					this.dataGridView1.Rows[0].Selected = true;
				}
				return;
			}
			this.indexId = this.dataGridView1.CurrentRow.Index;
			if (this.indexId < 0)
			{
				this.indexId++;
			}
			if (this.indexId > this.dataGridView1.Rows.Count - 1)
			{
				this.indexId--;
			}
			if (this.dataGridView1.RowCount > 1 && this.indexId >= 1)
			{
				this.dataGridView1.Rows[this.indexId].Selected = true;
				return;
			}
			this.dataGridView1.Rows[0].Selected = true;
		}

		private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
		{
		}

		private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
		{
			this.isEdit = true;
			if (this.treeView1.SelectedNode.Tag != null)
			{
				TreeviewValue treeviewValue = this.treeView1.SelectedNode.Tag as TreeviewValue;
				treeviewValue.IsEdit = true;
				DataTable dataGv = this.DataGridToDataTable(this.dataGridView1);
				treeviewValue.DataGv = dataGv;
			}
		}

		private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e.RowIndex > 0 && e.ColumnIndex > 0)
			{
				this.dataGridView1.CurrentCell = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
				this.dataGridView1.BeginEdit(true);
			}
		}

		private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
		{
		}

		private void CaculatRoomTypeManage_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (!this.isChecked)
			{
				e.Cancel = true;
				this.dgce.Cancel = true;
			}
		}

		public bool isCheckedValidata(string str)
		{
			bool result;
			try
			{
				Regex regex = new Regex("[~!@#$%^&*=+[\\]{}''\";/?.,><`|！·￥…—\\-；。》《]");
				Regex regex2 = new Regex("^\\d+(\\.\\d+)?$");
				if (regex.IsMatch(str))
				{
					MessageBox.Show("请输入合法字符");
					result = false;
				}
				else if (!regex2.IsMatch(str))
				{
					MessageBox.Show("格式不正确只能输入数字");
					result = false;
				}
				else
				{
					result = true;
				}
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}

		private void BtnAdd_Click(object sender, EventArgs e)
		{
			this.dataGridView1.Rows.Add();
			this.dataGridView1.ClearSelection();
			this.dataGridView1.Rows[this.dataGridView1.Rows.Count - 1].Selected = true;
			this.dataGridView1.FirstDisplayedScrollingRowIndex = this.dataGridView1.RowCount - 1;
		}

		private string roomTypeStr;

		private int indexId;

		private string[] roomTypeList;

		private bool isEdit;

		private bool isChecked = true;

		private List<string> DeleteId = new List<string>();

		private DataGridViewCellValidatingEventArgs dgce;
	}
}
